package io.persimmon.core.module.id.bo;

import org.apache.commons.collections4.CollectionUtils;

import java.util.List;

public abstract class ListBatchId<T> implements BatchId<T> {

    protected int batchSize;
    protected int index = 0;
    protected List<T> list;


    public ListBatchId(int batchSize) {
        if (batchSize < 1) {
            throw new IllegalArgumentException("size must be gte 1");
        }
        this.batchSize = batchSize;
        this.list = null;
    }

    @Override
    public T nextId() {
        synchronized (ListBatchId.class) {
            if (CollectionUtils.isNotEmpty(this.list) && index < this.list.size()) {
                return this.list.get(index++);
            } else {
                this.list = batchCreateId(this.batchSize);
                this.index = 0;
                return list.get(index++);
            }
        }
    }

    public abstract List<T> batchCreateId(int batchSize);
}
